package xipujewel.xipujewel.web.account;

import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.validation.Valid;

import net.esoar.modules.utils.WebUtil;
import net.esoar.modules.web.BaseController;
import net.esoar.modules.web.pojo.JPage;
import net.esoar.modules.web.pojo.WebPojo;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import xipujewel.xipujewel.entity.account.User;
import xipujewel.xipujewel.exceptions.ServiceException;
import xipujewel.xipujewel.pojo.authority.WebViews;
import xipujewel.xipujewel.service.account.UserManager;
import xipujewel.xipujewel.utils.UserUtil;

import com.google.common.collect.Lists;

/**
 * 用户管理
 * 
 * @author qizai
 * 
 */
@Controller
@RequestMapping(WebViews.SYSTEM_BASE_USER)
public class UserController extends BaseController<User> {
	// 权限及路径
	private final static String VIEW = WebViews.R_USER_VIEW;
	private final static String EDIT = WebViews.R_USER_EDIT;
	private final static String MODEL = WebViews.MODEL_USER;
	private final static String BASE_MAPPING = WebViews.SYSTEM_BASE_USER;

	@Autowired
	private UserManager userManager;

	/**
	 * 分页浏览
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(LIST)
	public String list(Model model, ServletRequest request) {
		Map<String, Object> searchParams = getFilters(request);
		initOrder("id", JPage.ASC);

		String currentUser = UserUtil.getCurrentUserLoginName();
		User cUser = userManager.findUserByLoginName(currentUser);
		if (cUser.getType() == 1) {
			searchParams.put("EQ_parent.id", cUser.getId());
		}

		jPage = userManager.search(searchParams, jPage);
		return getListView();
	}

	/**
	 * 新增或查看
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = INPUT, method = RequestMethod.GET)
	public String input(@PathVariable(ID) Long id, Model model) {
		User user = userManager.get(id);
		User cUser = userManager.findByLoginNameAndType01(UserUtil.getCurrentUserLoginName());
		model.addAttribute(getModelName(), user);
		model.addAttribute("cUser", cUser);
		if (id != 0) {
			return "account/user/user-update";
		}
		return getInputView();
	}

	/**
	 * 修改密码
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "toModifyPassword", method = RequestMethod.GET)
	public String toModifyPassword(Model model) {
		return getView("-modifyPassword");
	}

	@RequestMapping(value = "modifyPassword", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public WebPojo modifyPassword(@RequestParam(value = "oldPassword") String oldPassword,
			@RequestParam(value = "newPassword") String newPassword,
			@RequestParam(value = "newPasswordConfirm") String newPasswordConfirm) {
		try {
			User user = userManager.findUserByLoginName(UserUtil.getCurrentUserLoginName());
			if (user.getId() == 0L) {
				return WebUtil.getError("请登录后再修改密码。");
			}
			if (!user.getSourcePassword().equals(oldPassword)) {
				return WebUtil.getError("旧密码不正确。");
			}
			if (!newPasswordConfirm.equals(newPassword)) {
				return WebUtil.getError("确认密码与新密码不相同。");
			}
			if (StringUtils.equals(oldPassword, newPassword)) {
				return WebUtil.getError("新密码不能和旧密码相同。");
			}
			// 新密码强度校验
			user.setPlainPassword(newPassword);
			user.setSourcePassword(newPassword);
			user.setPassword(newPassword);
			userManager.save(user);
		} catch (ServiceException e) {
			logger.error("修改密码出错！", e);
			return WebUtil.getError(e.getMessage());
		}
		//		UserUtil.logout();
		return WebUtil.getCloseCurrent("", "修改成功");
	}

	/**
	 * 保存/更新
	 * 
	 * @param model
	 * @param checkedRoleList
	 * @return
	 */
	@RequestMapping(value = SAVE, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public WebPojo save(@Valid @ModelAttribute(MODEL) User model) {
		try {
			model.setSourcePassword(model.getPassword());
			userManager.save(model);
		} catch (ServiceException e) {
			logger.error("保存用户出错！", e);
			return WebUtil.getError(e.getMessage());
		}

		return WebUtil.getCloseCurrent(getTabId());
	}

	/**
	 * 删除固定id的记录
	 * 
	 * @param id
	 *            主键
	 * @return
	 */
	@RequestMapping(value = DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public WebPojo delete(@PathVariable(ID) Long id) {
		User user = userManager.get(id);
		if (user.getParent() != null && user.getParent().getId() != 0) {
			user.setParent(null);
			userManager.updateUser(user);
		}
		userManager.delete(user);
		return WebUtil.getNavTabAjaxDone(getTabId());
	}

	@RequestMapping(value = "proxy")
	public String getProxy(Model model) {
		List<User> users = userManager.findByType(1);
		model.addAttribute("users", users);
		return "account/user/proxySelect";
	}

	/**
	 * 根据主键Id批量删除记录
	 * 
	 * @param ids
	 *            主键集合
	 * @return
	 */
	@RequestMapping(value = DELETES, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public WebPojo deleteByIds(@RequestParam(IDS) List<Long> ids) {
		try {
			List<User> users = Lists.newArrayList();
			for (Long id : ids) {
				User user = userManager.get(id);
				if (user.getParent() != null && user.getParent().getId() != 0) {
					user.setParent(null);
					userManager.updateUser(user);
				}
				users.add(user);
			}
			for (User u : users) {
				userManager.delete(u);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return WebUtil.getNavTabAjaxDone(getTabId());
	}

	/**
	 * 使用@ModelAttribute, 实现Struts2
	 * Preparable二次部分绑定的效果,先根据form的id从数据库查出User对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此本方法在该方法中执行.
	 */
	@ModelAttribute(MODEL)
	public User getModel(@RequestParam(value = ID, required = false) Long id) {
		if (id != null) {
			return userManager.get(id);
		}
		return null;
	}

	/**
	 * 不自动绑定对象中的allRoles属性，另行处理。
	 */
	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		binder.setDisallowedFields("allRoles");
	}

	//
	@Override
	public String baseMapping() {
		return BASE_MAPPING;
	}

	@Override
	public String getModelName() {
		return MODEL;
	}

}
